package com.lemon.rpcframe.provider.handler;

import com.lemon.rpcframe.commons.DTaskProvider;
import com.lemon.rpcframe.commons.InjectorHolder;
import com.lemon.rpcframe.dao.entity.NodeGroupBean;
import com.lemon.rpcframe.rpc.netty5.MessageType;
import com.lemon.rpcframe.rpc.netty5.NettyMessage;
import com.lemon.rpcframe.util.SerializeUtil;
import com.lemon.rpcframe.util.StringUtils;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class NodeGroupPushHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        NettyMessage msg = (NettyMessage) obj;
        if (msg.getType() == MessageType.NodeGroupPush.value()) {
            msg.setTimestamp(System.currentTimeMillis());
            String nodetype = msg.getNodeType();
            String nodegroup = msg.getNodeGroup();
            if (!StringUtils.isNullOrEmpty(nodetype) && !StringUtils.isNullOrEmpty(nodegroup)) {
                InjectorHolder.getInstance(DTaskProvider.class).addNodeGroup(nodetype, nodegroup);
            }
            NodeGroupBean node = InjectorHolder.getInstance(DTaskProvider.class).getINodeGroupService().loadByTypeName(nodetype, nodegroup);
            if (node != null) {
                msg.setResultJson(SerializeUtil.jsonSerialize(node));
            }
            ctx.writeAndFlush(msg);
        } else {
            ctx.fireChannelRead(obj);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
